package com.easylinkin.linkappapi.afterloan.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.regex.Pattern;

/**
 * class info :
 *
 * @author liuqihang
 * @date 2021/4/27 13:47
 */
@Slf4j
public class HttpUtils {

    // 请登录http://yjapi.com/DataCenter/MyData
    // 查看我的秘钥 我的Key
    private static  String appkey = "04209e05be4f427cb43d205240fb3bbc";
    private static  String seckey = "326155B4BC2FE36DA2808308B8CA57A0";
    private static  String APIIP="http://api.qichacha.com/";

    public static String HttpGet(String reqInterNme,String paramStr) {
        String status = "";
        try {
            // auth header setting
            CloseableHttpClient httpclient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(60000)
                    .setConnectTimeout(60000)
                    .setConnectionRequestTimeout(60000)
                    .build();
            String[] autherHeader = RandomAuthentHeader();
            final String reqUri = APIIP.concat(reqInterNme).concat("?key=").concat(appkey).concat("&").concat(paramStr);
            log.info("http请求url:{}", reqUri);
            HttpGet httpGet = new HttpGet(reqUri);
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("Token", autherHeader[0]);
            httpGet.setHeader("Timespan", autherHeader[1]);

            CloseableHttpResponse httpResponse = httpclient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            log.info("http请求响应结果:{}", result);
            JSONObject jObject=JSONObject .parseObject(result);
            status = jObject.getString("Status");
            //200【有效请求】查询成功 201【有效请求】查询无结果
            if ("200".equals(status) || "201".equals(status)) {
                return result;
            }
            log.error("请求查询企查查接口失败：请求地址:{},请求参数:{},错误信息:{}",reqInterNme,paramStr,jObject.getString("Message"));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    // 获取返回码 Res Code
    static class HttpCodeRegex {
        private static final String ABNORMAL_REGIX = "(101)|(102)";
        private static final Pattern pattern = Pattern.compile(ABNORMAL_REGIX);
        protected static boolean isAbnornalRequest(final String status) {
            return pattern.matcher(status).matches();
        }
    }

    // 获取Auth Code
    protected static final String[] RandomAuthentHeader() {
        String timeSpan = String.valueOf(System.currentTimeMillis() / 1000);
        String[] authentHeaders = new String[] { DigestUtils.md5Hex(appkey.concat(timeSpan).concat(seckey)).toUpperCase(), timeSpan };
        return authentHeaders;
    }

    // 解析JSON
    protected static String FormartJson(String jsonString, String key) {
        JSONObject jObject=JSONObject .parseObject(jsonString);
        return (String) jObject.get(key);
    }
}
